package com.hellowx.qydcdev.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hellowx.qydcdev.constant.Constant;
import com.hellowx.qydcdev.dao.UserDao;
import com.hellowx.qydcdev.entity.User;
import com.hellowx.qydcdev.exception.CustomException;
import com.hellowx.qydcdev.exception.CustomExceptionType;
import com.hellowx.qydcdev.service.UserService;
import com.hellowx.qydcdev.utils.MD5Utils;
import com.hellowx.qydcdev.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Created on 2022/1/11.
 *
 * @author Hello WX
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public String login(User user) {
        User one = new LambdaQueryChainWrapper<>(userDao)
                .eq(User::getPhone, user.getPhone())
                .one();
        if (one==null){
            throw new CustomException(CustomExceptionType.USER_INPUT_EXCEPTION,"该用户不存在!!");
        }
        if (!MD5Utils.verifyPwd(user.getPassword(),one.getPassword())){
            throw new CustomException(CustomExceptionType.USER_INPUT_EXCEPTION,"密码错误!");
        }
        UUID uuid = UUID.randomUUID();
        String token = uuid +"_user_login_key";
        redisUtils.set(token,one,10800L);
        return token;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveUser(User user) {
        String msg;
        if (user.getId()==null){
            User one = new LambdaQueryChainWrapper<>(userDao)
                    .eq(User::getPhone, user.getPhone())
                    .one();
            if (one!=null){
                throw new CustomException(CustomExceptionType.USER_INPUT_EXCEPTION,"该手机号已绑定响应信息");
            }
            String password = MD5Utils.generatePwd(Constant.DEFAULT_PASSWORD);
            user.setPassword(password);
            userDao.insert(user);
            msg = "保存成功!!";
        }else {
            userDao.updateById(user);
            msg = "修改成功!!";
        }
        return msg;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPwd(Long userId) {
        User user = new User();
        user.setId(userId);
        String password = MD5Utils.generatePwd(Constant.DEFAULT_PASSWORD);
        user.setPassword(password);
        int rows = userDao.updateById(user);
        if (rows==0){
            throw new CustomException(CustomExceptionType.SYSTEM_EXCEPTION,"重置密码失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updatePassword(User user) {
        int rows = userDao.updateById(user);
        return rows>0 ? "修改成功" : "修改失败";
    }
}
